###############################################################
## TEXT MOTION
## This programs sends me a text when motion is detected.
##
## Motion Sensor:
## Connect PIR motion sensor to Raspberry Pi
##      - Vcc to GPIO 5V 
##      - Gnd to GPIO Gnd
##      - Signal to GPIO 18
##
## Text:
## A different python program is called to send the text.
##
## Delay:
## There's a delay time before the motion detection starts.
## Default is 30 seconds. Change it using the "-t" option.
###############################################################

import time, subprocess, getopt, sys
import RPi.GPIO as gpio

# use BCM pin numbers
gpio.setmode(gpio.BCM)
gpio.setwarnings(False)

# The pin that reads input signals from motion sensor
PIR_IN = 14
gpio.setup(PIR_IN, gpio.IN)


def main():
    try:
        # Read user-defined delay time. Default is 30 seconds
        input_time = readArgument("-t");
        if input_time is None:
            delay_time = 30
        else:
            delay_time = float(input_time)
        
        # Since it's directly connected to power, the sensor is already on.
        # Ignore the reading for the duration of delay_time.
        # After that, motion detection "officially" starts 
        log('Motion detection will start in ' + str(delay_time) + ' seconds')
        time.sleep(delay_time)
        log('Starting motion detection...')

        # while no motion detected, do nothing
        while not gpio.input(PIR_IN):
            pass
        
        # Motion detected, start music
        log('Motion Detected')
        sendTextMsg('Pi Motion Sensor', 'Movement has been detected in your apartment') 
        
    except KeyboardInterrupt:
        log('Program stopped by user.')
        gpio.cleanup()


def sendTextMsg(subject, message):
    run('sudo python mailsender.py -t -m "' + message +' on ' + time.strftime("%A, %B %d, %Y  %I:%M:%S %p") + '" -s "' + subject + '"')


# Execute shell command
def run(command):
    subprocess.call(command, shell=True)

# Read command-line argument of the given option
def readArgument(option):
    opts, args = getopt.getopt(sys.argv[1:], "t:")
    for opt, arg in opts:
        if opt == option:
            return arg


def log(logmsg):
	print("{}\t{}".format(time.strftime("%Y-%m-%d %H:%M:%S"), logmsg))

if __name__=="__main__":main()
